﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;


namespace YFrameWork.RunTime
{
    public class DataComponent : YFrameWorkComponent
    {

        private readonly  Dictionary<Type, IData> DatasDic = new Dictionary<Type, IData>();
        public override void ToCreate()
        {
        }

        private void OnApplicationPause(bool pause)
        {
            if (pause) SaveAllData();
        }
        bool isFocus = true;
        private void OnApplicationFocus(bool focus)
        {
            if (!focus) SaveAllData();
            if (!isFocus && focus )
            {
                //TODO 重新返回游戏
                //AD.ShowInterstialAd(null, "返回游戏");
            }
            isFocus = focus;

        }
        private void OnApplicationQuit()
        {
            SaveAllData();
        }
        /// <summary>
        /// 获取一个数据类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetData<T>() where T : class,IData 
        {
            Type type = typeof(T);
            T t = null;
            if (DatasDic.ContainsKey(type))
            {
                t = DatasDic[type] as T;
            }
            else
            {
                t = Activator.CreateInstance<T>();
                DatasDic.Add(type, t);
            }
            return t;
        }

        public void SaveAllData()
        {
            foreach (var item in DatasDic.Values)
            {
                item.SaveData();
            }
        }



        public void ClearAllData()
        {
            foreach (var item in DatasDic)
            {
                DataBase dataBase = (DataBase)item.Value;
                dataBase.Clear();
            }
        }


       
    }
}